//
//  CXHTopOnCommonBiddingManager.m
//  CXHAdSDK-TopOn
//
//  Created by 陈坤 on 2024/10/14.
//

#import "CXHTopOnCommonBiddingManager.h"
#import <CXHAdSDK-Core/CXHAdSDK.h>
#import <CXHAdSDK-Core/CXHAdSDKBannerAdView.h>
#import <CXHAdSDK-Core/CXHAdSDKInterstitialAd.h>
#import <CXHAdSDK-Core/CXHAdSDKNativeExpressAd.h>
#import <CXHAdSDK-Core/CXHAdSDKNativeAd.h>
#import <CXHAdSDK-Core/CXHAdSDKSplashAd.h>
#import "CXHTopOnInterstitialEvent.h"
#import "CXHTopOnNativeExpressEvent.h"
#import "CXHTopOnNativeEvent.h"
#import "CXHTopOnBannerEvent.h"
#import "CXHTopOnSplashCustomEvent.h"

@interface CXHTopOnCommonBiddingManager ()

@property(nonatomic, strong) NSMutableDictionary<NSString *, id> *requestDic;


@end

@implementation CXHTopOnCommonBiddingManager

+ (instancetype)sharedInstance {
    static CXHTopOnCommonBiddingManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[CXHTopOnCommonBiddingManager alloc] init];
    });
    return sharedInstance;
    
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _requestDic = [NSMutableDictionary dictionary];
    }
    return self;
}

#pragma mark - request CRUD
- (void)saveRequestItem:(id)request withUnitId:(NSString *)unitID{
    @synchronized (self) {
        [self.requestDic setValue:request forKey:unitID];
    }
}

- (id)getRequestItemWithUnitID:(NSString*)unitID {
    @synchronized (self) {
        return [self.requestDic objectForKey:unitID];
    }
}

- (void)removeRequestItemWithUnitID:(NSString*)unitID {
    @synchronized (self) {
        [self.requestDic removeObjectForKey:unitID];
    }
}

- (void)startWithRequestItem:(CXHTopOnCommonBiddingRequest *)request {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self saveRequestItem:request withUnitId:request.UUID];
        switch (request.adType) {
                
            case CXHAdFormatInterstitial:
                
                [self startLoadInterstitialAdWithRequest:request];
                break;
                
            case CXHAdFormatRewardedVideo:
                [self startLoadRewardedVideoAdWithRequest:request];
                break;
            
            case CXHAdFormatNative:
                [self startLoadNativeAdWithRequest:request];
                break;
                
            case CXHAdFormatSplash:
                [self startLoadSplashAdWithRequest:request];
                break;

            case CXHAdFormatBanner:
                // 原生混横幅，原生用作横幅
                [self startLoadNativeBannerAdWithRequest:request];
                break;
                
            default:
                break;
        }
    });
}

#pragma mark - ATAdFormatInterstitial
- (void)startLoadInterstitialAdWithRequest:(CXHTopOnCommonBiddingRequest *)request {
    NSString *adslot_id_str = request.unitGroup.content[@"posid"];
//    NSString *adslot_id_str = [NSString stringWithFormat:@"%@",request.unitGroup.content[@"adslot_id"]];
    
    CXHTopOnInterstitialEvent *customEvent = (CXHTopOnInterstitialEvent *)request.customEvent;
    
    CXHAdSDKInterstitialAd *interstitialAd = [[CXHAdSDKInterstitialAd alloc] init];
    interstitialAd.delegate = customEvent;
    interstitialAd.posId = adslot_id_str;
    request.customObject = interstitialAd;
    
    [interstitialAd loadAdData];

}

#pragma mark - ATAdFormatRewardedVideo
- (void)startLoadRewardedVideoAdWithRequest:(CXHTopOnCommonBiddingRequest *)request {
    NSString *adslot_id_str = request.unitGroup.content[@"posid"];
    
//    QuMengRewardedVideoAd *rewardAd = [[QuMengRewardedVideoAd alloc] initWithSlot:adslot_id_str];
//    request.customObject = rewardAd;
//    
//    CustomAdapterRewardVideoCustomEvent *customEvent = (CustomAdapterRewardVideoCustomEvent *)request.customEvent;
//    rewardAd.delegate = customEvent;
//    [rewardAd loadAdData];
    
}

#pragma mark - ATAdFormatNative
- (void)startLoadNativeAdWithRequest:(CXHTopOnCommonBiddingRequest *)request {
    
    NSDictionary *serverInfo = request.extraInfo;
    
    BOOL isExpress = [serverInfo[@"isExpressAd"] boolValue];
    UIViewController *controller = serverInfo[@"cxh_controller"];
    int count = [serverInfo[@"request_num"] intValue];
    NSString *adslot_id_str = request.unitGroup.content[@"posid"];
    if (isExpress) {
        CXHTopOnNativeExpressEvent *expressCustomEvent = (CXHTopOnNativeExpressEvent *)request.customEvent;
        CGSize adSize = [serverInfo[kATExtraInfoNativeAdSizeKey] CGSizeValue];

        CXHAdSDKNativeExpressAd *nativeExpressAd = [[CXHAdSDKNativeExpressAd alloc] initWithAdSize:adSize];
        nativeExpressAd.posId = adslot_id_str;
        nativeExpressAd.delegate = expressCustomEvent;
        
        request.customObject = nativeExpressAd;
        if (controller) {
            nativeExpressAd.controller = controller;
        }
        [nativeExpressAd load:count];
    } else {
        CXHTopOnNativeEvent *nativeCustomEvent = (CXHTopOnNativeEvent *)request.customEvent;
        
        // 自渲染
        CXHAdSDKNativeAd *nativeAd = [[CXHAdSDKNativeAd alloc] init];
        nativeAd.posId = adslot_id_str;
        nativeAd.delegate = nativeCustomEvent;
        if (controller) {
            nativeAd.controller = controller;
        }
//        UIViewController *controller = localInfo[@"cxh_controller"];
//        nativeAd.controller = controller;
        
        request.customObject = nativeAd;
        [nativeAd load:count];
    }

}

#pragma mark - ATAdFormatBanner
- (void)startLoadNativeBannerAdWithRequest:(CXHTopOnCommonBiddingRequest *)request {
    
    NSDictionary *serverInfo = request.extraInfo;
    NSString *adslot_id_str = request.unitGroup.content[@"posid"];
    UIViewController *controller = serverInfo[@"cxh_controller"];
    
    CGSize bannerSize = [serverInfo[kATAdLoadingExtraBannerAdSizeKey] CGSizeValue];
    CXHTopOnBannerEvent *bannerEvent = (CXHTopOnBannerEvent *)request.customEvent;
    
    CXHAdSDKBannerAdView *bannerView = [[CXHAdSDKBannerAdView alloc] initWithFrame:CGRectMake(0, 0, bannerSize.width, bannerSize.height)];
    bannerView.delegate = bannerEvent;
    bannerView.posId = adslot_id_str;
    
    request.customObject = bannerView;
    if (controller) {
        bannerView.controller = controller;
    }
    [bannerView loadAndShow];

}

#pragma mark - ATAdFormatSplash
- (void)startLoadSplashAdWithRequest:(CXHTopOnCommonBiddingRequest *)request {
    
    NSString *adslot_id_str = request.unitGroup.content[@"posid"];
    
    CXHTopOnSplashCustomEvent *event = (CXHTopOnSplashCustomEvent *)request.customEvent;
    
    CXHAdSDKSplashAd *splashAd = [[CXHAdSDKSplashAd alloc] init];
    splashAd.posId = adslot_id_str;
    splashAd.delegate = event;
    splashAd.setSkipButtonToRightTop = YES;
    request.customObject = splashAd;
    [splashAd loadSplashAd];
}

- (void)disposeLoadSuccessCall:(NSString *)priceStr customObject:(id)customObject unitID:(NSString *)unitID {
    if (!priceStr || [priceStr doubleValue] < 0) {
        priceStr = @"0";
    }
    
    CXHTopOnCommonBiddingRequest *request = [self getRequestItemWithUnitID:unitID];
    if (request == nil) {
        return;
    }
    
    NSLog(@"%@",[NSString stringWithFormat:@"Qumeng::meta.getECPM:price:%@",priceStr] );

    //currencyType，第三方SDK返回的价格单位需要和currencyType枚举值匹配。也建议您将第三方SDK的价值转换为美元传入
    
    ATBidInfo *bidInfo = [ATBidInfo bidInfoC2SWithPlacementID:request.placementID unitGroupUnitID:request.unitGroup.unitID adapterClassString:request.unitGroup.adapterClassString price:priceStr currencyType:ATBiddingCurrencyTypeCNYCents expirationInterval:request.unitGroup.bidTokenTime customObject:customObject];
//    bidInfo.networkFirmID = request.unitGroup.networkFirmID;
//    bidInfo.curRate = [ATGeneralTool handleRateForBidInfo:bidInfo];
    if (request.bidCompletion) {
        request.bidCompletion(bidInfo, nil);
    }

}

- (void)disposeLoadFailCall:(NSError *)error key:(NSString *)keyStr unitID:(NSString *)unitID {
    CXHTopOnCommonBiddingRequest *request = [self getRequestItemWithUnitID:unitID];
    
    if (request == nil) {
        return;
    }
    
    if (request.bidCompletion) {
        request.bidCompletion(nil, [NSError errorWithDomain:@"com.anythink.Qumeng" code:error.code userInfo:@{
            NSLocalizedDescriptionKey:keyStr,
            NSLocalizedFailureReasonErrorKey:error}]);
    }

    [self removeRequestItemWithUnitID:request.unitGroup.content[@"adslot_id"]];

}
@end
